package com.toprs.base.utils

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.exceptions.JWTDecodeException
import com.auth0.jwt.exceptions.TokenExpiredException
import com.toprs.base.entity.User
import org.springframework.stereotype.Component
import java.util.*

@Component
class JwtUtil {


    companion object {
        private val algorithm: Algorithm by lazy {
            Algorithm.HMAC256("j2gxwjOZjoIHQ4fH/yqa7gP1lFOYtEBP")
        }

        fun createToken(user: User): String {
            val tt = mapOf("company" to "toprs", "type" to "JWT")
            return JWT.create().withHeader(tt)
                    .withClaim("username", user.username).withClaim("userId", user.userid.toString())
                    .withIssuer("toprs")
                    .withExpiresAt(Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))
                    .sign(algorithm)
        }


        @Throws(JWTDecodeException::class, TokenExpiredException::class)
        fun verify(token: String): Map<String, String> {
            val encode = JWT.require(algorithm).withIssuer("toprs").build().verify(token)
            return mapOf(
                    "username" to encode.getClaim("username").asString(),
                    "userId" to encode.getClaim("userId").asString()
            )
        }

    }
}